﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;

namespace Fusion
{
	public class Sound
	{
		public SoundEffect effect;
		public float timer;
		public float cooldown = 0.1f;

		public Sound( SoundEffect e )
		{
			effect = e;
		}

		public void Play()
		{
			if( effect == null || timer > 0 )
				return;

			effect.Play();

			timer = cooldown;
		}

		public void Play( float volume, float pitch, float pan )
		{
			if( effect == null || timer > 0 )
				return;

			effect.Play( volume, pitch, pan );

			timer = cooldown;
		}

		public void Update()
		{
			if( timer > 0 )
				timer -= Engine.period;
		}
	}

	// Sound manager
	public class Noisemaker
	{
		static Dictionary<string,Sound> sounds = new Dictionary<string,Sound>();

		public Noisemaker()
		{
			sounds = new Dictionary<string,Sound>();
		}

		public static void Play( string name )
		{
			if( !sounds.ContainsKey( name ) )
			{
				SoundEffect effect = Engine.Sounds.Get( name );
				if( effect == null )
					return;
				sounds.Add( name, new Sound( effect ) );
			}

			sounds[name].Play();
		}

		public static void Play( string name, float volume, float pitch, float pan )
		{
			if( !sounds.ContainsKey( name ) )
			{
				SoundEffect effect = Engine.Sounds.Get( name );
				if( effect == null )
					return;
				sounds.Add( name, new Sound( effect ) );
			}

			sounds[name].Play( volume, pitch, pan );
		}

		public static void Update()
		{
			foreach( Sound sound in sounds.Values )
				sound.Update();
		}
	}

}
